package com.thinvent.remotepassword.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.thinvent.remotepassword.entity.VetSource;
import com.thinvent.remotepassword.entity.VetTarget;
import com.thinvent.remotepassword.main.*;
import com.thinvent.remotepassword.util.SimilarityUtil;
import lombok.SneakyThrows;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/vet")
public class VetController {

    @Resource
    private VetSourceMapper vetSourceMapper;

    @Resource
    private VetTargetMapper vetTargetMapper;

    @GetMapping("/vet")
    public String getVet() {
        new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                Map<CQProject, List<CQBasePro>> resultMap = new HashMap<>();
                System.out.println("正在查询重庆重大库信息，请稍等...");
                List<CQProject> allCQProjects = DmDatabaseUtils.findAllCQProjects(DmDatabaseUtils.getConnection());
                System.out.println("重庆重大库数据查询完毕，总共有：" + allCQProjects.size() + "条数据");
                System.out.println("开始转化重庆重大库信息向量，请稍后...");
                allCQProjects.stream().forEach(cqProject -> {
                    // 法人单位
                    String gj_pro_org = cqProject.getGj_pro_org();
                    // 项目名称
                    String gj_pro_name = cqProject.getGj_pro_name();
                    try {
                        VetSource vet = new VetSource();
                        vet.setId(cqProject.getId());
                        vet.setGjProOrg(cqProject.getGj_pro_org());
                        vet.setGjProName(cqProject.getGj_pro_name());
                        vet.setGjMainBuildScale(cqProject.getGj_main_build_scale());
                        vet.setVetSource(SimilarityUtil.getVet(gj_pro_name));
                        vetSourceMapper.insert(vet);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });

                System.out.println("正在查询对比信息，请稍等...");
                List<CQBasePro> allCQBaseProsGroupedByGjProName = DmDatabaseUtils.findAllCQBaseProsGroupedByGjProName(DmDatabaseUtils.getConnection(), 10);
                System.out.println("对比数据查询完毕，总共有：" + allCQBaseProsGroupedByGjProName.size() + "条数据");
                System.out.println("开始转化对比数据信息向量，请稍后...");
                allCQBaseProsGroupedByGjProName.stream().forEach(cqBasePro -> {
                    try {
                        // 法人单位
                        String gj_pro_org = cqBasePro.getGj_pro_org();
                        // 项目名称
                        String gj_pro_name = cqBasePro.getGj_pro_name();
                        try {
                            VetTarget vet = new VetTarget();
                            vet.setId(cqBasePro.getId());
                            vet.setGjProOrg(cqBasePro.getGj_pro_org());
                            vet.setGjProName(cqBasePro.getGj_pro_name());
                            vet.setGjMainBuildScale(cqBasePro.getGj_main_build_scale());
                            vet.setVetTarget(SimilarityUtil.getVet(gj_pro_name));
                            vetTargetMapper.insert(vet);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } catch (Throwable throwable) {
                        throwable.printStackTrace();
                    }
                });

            }
        }).start();
        return "success";
    }

    @GetMapping("/excel")
    public String getResult() {
        List<CombinedData> dataList = new ArrayList<>();
        List<VetSource> vetSources = vetSourceMapper.selectList(null);
        // 使用Stream API过滤掉法人单位为空的记录
        List<VetSource> filteredVetSources = vetSources.stream()
                .filter(data -> !data.getId().equals("法人单位为空"))
                .collect(Collectors.toList());
        filteredVetSources.stream().forEach(vetSource -> {
            // 根据id去查询数据库
            QueryWrapper<VetTarget> wrapper = new QueryWrapper();
            wrapper.eq("id", vetSource.getId());
            List<VetTarget> vetTargets = vetTargetMapper.selectList(wrapper);
            if(CollectionUtils.isNotEmpty(vetTargets)) {
                // 对比相似度
                vetTargets.stream().forEach(vetTarget -> {
                    double v = SimilarityUtil.cosineSimilarity(SimilarityUtil.strToDoubleArray
                            (vetSource.getVetSource()), SimilarityUtil.strToDoubleArray(vetTarget.getVetTarget()));
                    if(v >= 0.6) {
                        // 当 cqBasePros 为空或不存在时，只添加与 CQProject 相关的字段
                        CombinedData data = new CombinedData(
                                vetSource.getId(),
                                vetSource.getGjProName(),
                                vetSource.getGjProOrg(),
                                vetSource.getGjMainBuildScale(),
                                vetTarget.getId(),
                                vetTarget.getGjProName(),
                                vetTarget.getGjProOrg(),
                                vetTarget.getGjMainBuildScale()
                        );
                        dataList.add(data);
                    } else {
                        // 当 cqBasePros 为空或不存在时，只添加与 CQProject 相关的字段
                        CombinedData data = new CombinedData(
                                vetSource.getId(),
                                vetSource.getGjProName(),
                                vetSource.getGjProOrg(),
                                vetSource.getGjMainBuildScale(),
                                null, // target 相关字段设置为 null
                                null,
                                null,
                                null
                        );
                        dataList.add(data);
                    }
                });
            }
        });
        String exportFilePath = "data/CombinedData.xlsx";
        ExcelExporter.exportCombinedDataList(dataList, exportFilePath);
        System.out.println("Export successful!");
        return null;
    }

}
